package dshop.interceptor;

import java.util.UUID;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import appbase.jfinal.ext.ApiBaseController;
import appbase.kit.encrypt.MD5Kit;
import dshop.AppConst;
import dshop.service.RedisService;

public class ApiAuthInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation ai) 
	{
		//ai.invoke();
		
		Controller ctrl = ai.getController();
		String token = ctrl.getPara(ApiBaseController.PARAM_API_KEY_TOKEN);
		Integer userId = ctrl.getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID);
		
		if (verifyToken(token, userId))
		{
			ai.invoke();
			return;
		}
		
		ctrl.setAttr(AppConst.RESPONSE_KEY_CODE, AppConst.RESPONSE_VALUE_CODE_UNAUTHENTICATION);
		ctrl.setAttr(AppConst.RESPONSE_KEY_MSG, "会话已经失效，请重新登录");
		ctrl.renderJson();
	}
	
	public static String createToken(int userId)
	{
		return MD5Kit.encrptMD5(UUID.randomUUID().toString() + "-" + userId);
	}

	public boolean verifyToken(String token, Integer userId) 
	{
		if (token == null || token.isEmpty() || userId == null || userId < 0) 
		{
			return false;
		}

		Integer cacheUserId = RedisService.getApiUserId(token);
		return cacheUserId != -1 && userId.equals(cacheUserId);
		//return true;
	}
	
}
